import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './newcomerenjoy.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Popup, SearchBar, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import icon_new_comer_enjoy_bg from '@/assets/icon_new_comer_enjoy_bg.png'
import icon_add_white from '@/assets/icon_add_white.png'

import NavigateBar from "@/components/NavigateBar";
import QRCode from "qrcode.react";
import { getCoinInfo, isUnvalidUserInfo, setCoinInfo, setTransferInfo } from "@/utils/storage";
import { toCopyText, toPercentageString } from "@/utils/utils";
import { LangThai } from '@/utils/langThai';
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import { getFirstRechargeConfig, getNewComerEnjoy } from "@/store/actions/newComerEnjoy";
import { getCoins } from "@/store/actions/coins";

/**
 * 首充返利页
 */
export default function NewComerEnjoy() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // transfer 弹框
    const [transferMaskVisible, setTransferMaskVisible] = useState(false)
    // 当前币
    const [curCoinName, setCurCoinName] = useState('')
    // 当前 coin 列表
    const [curCoinList, setCurCoinList] = useState([])
    const [curCoinListTemp, setCurCoinListTemp] = useState([])
    // 当前 wallet fliter
    const [curTransferText, setCurTransferText] = useState("")


    // 当前配置
    const [firstRechargeConfig, setFirstRechargeConfig] = useState("");

    // 是否完成首充
    const [firstRechargeDone, setFirstRechargeDone] = useState(true);
    const [income, setIncome] = useState("*");
    const [amount, setAmount] = useState("*");

    // 当前币
    const [curCoinInfo, setCurCoinInfo] = useState({ address: "" });

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //router

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 判断是否需要重登录
        if (isUnvalidUserInfo()) {
            history.replace('/login')
            return
        }

        // 获取配置
        doGetFirstRechargeConfig();

        // 获取首充信息
        doGetNewComerEnjoy()

        // 读取缓存
        // const coinInfo = getCoinInfo();
        // let gCoinInfo = { ...coinInfo };
        // setCurCoinInfo(gCoinInfo);

        //打点
        doHitEvent("NEW_COMER_ENJOY_START")

        return () => {
            //打点
            // doHitEvent("NEW_COMER_ENJOY_END")
        }
    }, [])

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取首充配置
    const doGetFirstRechargeConfig = async () => {
        console.log("doGetFirstRechargeConfig: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getFirstRechargeConfig(onDoGetFirstRechargeConfigCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取首充详情
    const doGetNewComerEnjoy = async () => {
        console.log("doGetNewComerEnjoy: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getNewComerEnjoy(onDoGetNewComerEnjoyCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取币种信息
    const doGetCoins = async () => {
        console.log("doGetCoins: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getCoins(onDoGetCoinsCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取币种信息 返回
    const onDoGetCoinsCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取币种信息接口 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            if (data.length > 0) {
                // {
                //     "symbol": "BTC",
                //     "coinName": null,
                //     "name": "BTC",
                //     "mainCoinType": "0",
                //     "coinType": "0",
                //     "logo": null,
                //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
                //     "balance": 0
                // }

                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    let coinName = item.coinName || "";
                    let name = item.name || "";
                    let symbol = item.symbol || "";
                    let mainCoinType = item.mainCoinType || "";
                    let coinType = item.coinType || "";
                    let logo = item.logo || icon_add_white;
                    let address = item.address || "";

                    if (coinName.length === 0) {
                        coinName = symbol;
                    }

                    item.coinName = coinName;
                    item.name = name;
                    item.logo = logo;
                    item.address = address;
                    item.symbol = symbol;
                    item.mainCoinType = mainCoinType;
                    item.coinType = coinType;
                }

                // 缓存
                setCurCoinListTemp(data);
                setCurCoinList(data);
                setTransferMaskVisible(true);
            }
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // 获取首充配置 返回
    const onDoGetFirstRechargeConfigCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取首充配置 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            if (data.length > 0) {
                let rate = toPercentageString(data);
                setFirstRechargeConfig(rate)
            }
        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // 获取首充详情 返回
    const onDoGetNewComerEnjoyCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取首充详情 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            let first = data.first || "YES";
            let done = first === "YES";
            setFirstRechargeDone(done);

            let income = data.income || "*";
            let amount = data.amount || "*";
            setIncome(income);
            setAmount(amount);

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // 点击去transfer in
    const onHandleToTransfer = () => {
        // 查询币
        doGetCoins();
    };

    // 点击 transfer item
    const onHandleTransferItemClick = (item) => {
        if (item) {
            console.log('点击 transfer item: ');
            console.log(item);

            let transferInfo = {};
            transferInfo.name = item.coinName || "";
            transferInfo.coinType = item.coinType || "";
            // 缓存
            setTransferInfo(transferInfo)

            history.push('/transfer');
        }
    };

    // 过滤 transfer item
    const onHandleTransferTextChanged = (text) => {
        console.log('更新 输入框: ' + text);
        // 更新 输入框
        setCurTransferText(text);

        // 更新列表
        let textUp = text.toUpperCase();
        let sourceList = [...curCoinListTemp];
        let tempList = [];
        for (let i = 0; i < sourceList.length; i++) {
            let item = sourceList[i];
            if (item.coinName.indexOf(textUp) !== -1) {
                tempList.push(item);
            } else if (item.name.indexOf(textUp) !== -1) {
                tempList.push(item);
            }
        }
        setCurCoinList(tempList);
    };


    return (
        <div className={styles.newComerEnjoyRoot}>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.newComerWelfare}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull pageContentPaddingHorizontal16px">

                {/* banner 模块 */}
                <div className={styles.newComerEnjoyBannerContent}>
                    <img className={styles.newComerEnjoyBanner} src={icon_new_comer_enjoy_bg} alt="" />

                    <div className={styles.newComerEnjoyBannerTextContent}>
                        <div className={styles.newComerEnjoyBannerTitle}>{curLang.newComerWelfareBanner1}</div>
                        <div className={styles.newComerEnjoyBannerDetail}>{firstRechargeConfig} {curLang.newComerWelfareBanner2}</div>
                    </div>
                </div>

                {/* amount 模块 */}
                <div className={styles.newComerEnjoySectionContent}>
                    <div className={styles.newComerEnjoyTipDetail}>{curLang.newComerWelfareTransfer1} {firstRechargeConfig} {curLang.newComerWelfareTransfer11}</div>

                    <div className={styles.newComerEnjoyAmountContent}>
                        <div className={styles.newComerEnjoyAmountTitle}>{curLang.newComerWelfareTransfer2}</div>
                        <div className={styles.newComerEnjoyAmountDetail}>{income} USDT</div>
                    </div>

                    <div className={styles.newComerEnjoyAmountContent}>
                        <div className={styles.newComerEnjoyAmountTitle}>{curLang.newComerWelfareTransfer3}</div>
                        <div className={styles.newComerEnjoyAmountDetail}>{amount} USDT</div>
                    </div>


                    {firstRechargeDone && <div className={styles.newComerEnjoyAmountTransferUnable}>{curLang.newComerWelfareTransfer4}</div>}
                    {!firstRechargeDone && <div className={styles.newComerEnjoyAmountTransfer} onClick={onHandleToTransfer}>{curLang.newComerWelfareTransfer4}</div>}

                </div>

                {/* tips 模块 */}
                <div className={styles.newComerEnjoySectionContent}>
                    <div className={styles.newComerEnjoyTipTitle}>{curLang.newComerWelfareTipsTitle}</div>
                    <div className={styles.newComerEnjoyTipDetail}>{curLang.newComerWelfareTipsDetail} {firstRechargeConfig} {curLang.newComerWelfareTipsDetail2}</div>
                </div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* 左上角切换 */}
            <Popup
                visible={transferMaskVisible}
                onMaskClick={() => {
                    setTransferMaskVisible(false)
                }}
                bodyStyle={{
                    height: '80vh',
                    borderTopLeftRadius: '16px',
                    borderTopRightRadius: '16px'
                }}
                destroyOnClose
            >
                <div className={styles.newComerEnjoyBarContainer}>
                    <div className={styles.newComerEnjoyBarLine}></div>
                    <div className={styles.newComerEnjoyBarTitle}>{curLang.homeSelectAsset}</div>
                    <div className={styles.newComerEnjoyBarValue}>{curCoinName}</div>
                    <SearchBar
                        style={{ width: '100%' }}
                        placeholder='Input Token Name'
                        value={curTransferText}
                        onChange={v => {
                            onHandleTransferTextChanged(v);
                        }} />
                </div>

                <div className={styles.newComerEnjoyPopupContainer}>
                    {/* Assets 列表 */}
                    <div className={styles.newComerEnjoyAssetsList}>
                        {curCoinList && curCoinList.map((value, index) => {
                            return (
                                <div className={styles.newComerEnjoyAssetsListItem} key={index} onClick={() => { onHandleTransferItemClick(value) }}>
                                    <img className={styles.newComerEnjoyAssetsListItemIcon} alt="" src={value.logo} />
                                    <div className={styles.newComerEnjoyAssetsListItemName}>{value.coinName}</div>
                                    <div className={styles.newComerEnjoyAssetsListItemAmount}>{value.balance}</div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </Popup>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}